package agriculture.service.impl;

import agriculture.bean.Comment;
import agriculture.bean.Product;
import agriculture.dto.StockDTO;
import agriculture.feign.UserClient;
import agriculture.mapper.ProductMapper;
import agriculture.service.ProductService;
import agriculture.system.api.model.User;
import agriculture.util.Result;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    //注入 OpenFeign 客户端
    @Autowired
    private UserClient userClient;

    @Override
    public List<Product> getActiveProducts() {
        return productMapper.findAllActiveProducts();
    }

    @Override
    public List<Product> getProductsByCategory(Long categoryId) {
        return productMapper.findProductsByCategory(categoryId); // 👈 调用新 SQL
    }

    //查询商品详细
    @Override
    public List<Product> selectProductDetail(Long id) {
        return productMapper.selectProductDetail(id);
    }

    /**
     * 获取商品对应的评论信息
     * @param productId
     * @return
     */
    @Override
    public List<Comment> getCommentsByProductId(Long productId) {
        System.out.println("实现类的productId=" + productId);
        //查询评论数据
        List<Comment> comments = productMapper.getCommentsByProductId(productId);

        //用于解析JSON
        ObjectMapper objectMapper = new ObjectMapper();
        //遍历评论列表，填充用户数据
        for (Comment comment : comments) {
            //解析img字段,商品用户评论的图片不止一张，需要变为数组的形式
            if (comment.getImg() != null | comment.getImg().isEmpty()) {
                try {
                    List<String> imgList = objectMapper.readValue(comment.getImg(), List.class);
                    comment.setImgList(imgList);
                } catch (Exception e) {
                    //如果不是合法JSON,就当成单个图片处理
                    comment.setImgList(List.of(comment.getImg()));
                }
            }
            //远程调用
            Result<User> result = userClient.getUserById(comment.getUserId());
//            System.out.println("远程调用的结果"+result.getData());
//            System.out.println("状态码："+result.getCode());
//            System.out.println("---------------------------------------");
            if (result !=null && result.getCode() == 200 && result.getData() != null) {
                System.out.println("进入条件");
                //获取用户服务返回的User对象
                User userFromService = result.getData();
                //将其对象映射到Comment.User
               Comment.User user = new Comment.User();
               user.setId(userFromService.getId());
               user.setUsername(userFromService.getUsername());
               user.setAvatar(userFromService.getAvatar());

               //将映射后的用户信息设置到 Comment 对象中
                comment.setUser(user);
            }else {
                // 执行 fallback
                System.out.println("远程调用失败，fallback 被触发");
            }
        }
        return  comments;
    }

    /**
     * 扣减商品库存业务逻辑，使用乐观锁防止超卖
     * @param stockDTO
     * @return
     */
    @Override
    public boolean decreaseStock(StockDTO stockDTO) {
        //查询对应的商品信息
        Product product = productMapper.selectById(stockDTO.getProductId());
        // 判断商品是否存在和库存是否足够
        if (product == null) {
            System.out.println("商品不存在，扣减失败！");
            return false;
        }
        if (product.getStock() < stockDTO.getQuantity()) {
            System.out.println("库存不足，扣减失败！");
            return false;
        }

        //构造更新条件，带version乐观锁
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", product.getId())
                .eq("version", product.getVersion())
                .set("stock",product.getStock() - stockDTO.getQuantity())
                .set("version",product.getVersion()+1); //version 加 1

        //执行更新
        int rows = productMapper.update(product, updateWrapper);
        if (rows ==1) {
            log.info("商品库存扣减成功，商品ID={},扣减数量={}", stockDTO.getProductId(), stockDTO.getQuantity());
            return true;
        }else {
            log.warn("商品库存扣减失败（可能是并发导致的version不匹配），商品ID={},当前版本version={}", stockDTO.getProductId(), stockDTO.getQuantity());
            return false;
        }
    }


}
